/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */

var connect = function (root) {
    if (!root) {
        return null
    } else {
        let queue = []
        let res = []
        queue.push(root)
        while (queue.length) {
            let len = queue.length
            // 队列中如果群在元素
            while (len) {
                // 取队首
                let node = queue.shift()
                if (len !== 1) {
                    node.next = queue[0]
                }
                if (node.left) {
                    queue.push(node.left)
                }
                if (node.right) {
                    queue.push(node.right)
                }
                len--
            }
        }
    }
    return root
};